﻿using UnityEngine;
using System.Collections;

/// <summary>
/// Sprite sheet.
/// </summary>
/// <see cref="http://wiki.unity3d.com/index.php?title=Animating_Tiled_texture"/>
public class SpriteSheet : MonoBehaviour {

	public int _uvTieX = 1;
	public int _uvTieY = 1;
	public int _fps = 10;
 
	private Vector2 _size;
	private Renderer _myRenderer;
	private int _lastIndex = -1;
	
	public bool canAnimate;
 
	void Start () 
	{
		_size = new Vector2 (1.0f / _uvTieX , 1.0f / _uvTieY);
		_myRenderer = renderer;
		if(_myRenderer == null)
			enabled = false;
	}
	
	void Update()
	{
		AnimateSprite();
	}
	
	public void AnimateSprite()
	{
		if (canAnimate)
		{
			// Calculate index
			int index = (int)(Time.timeSinceLevelLoad * _fps) % (_uvTieX * _uvTieY);
	    	if(index != _lastIndex)
			{
				// split into horizontal and vertical index
				int uIndex = index % _uvTieX;
				//int vIndex = index / _uvTieY;
	 
				// build offset
				// v coordinate is the bottom of the image in opengl so we need to invert.
				Vector2 offset = new Vector2 (uIndex * _size.x, 0);
	 
				_myRenderer.material.SetTextureOffset ("_MainTex", offset);
				_myRenderer.material.SetTextureScale ("_MainTex", _size);
	 
				_lastIndex = index;
			}
		}
	}
}
